<?php

namespace app\api\controller;


use app\admin\model\User\Friend;
use app\admin\model\User\Msg;
use app\common\controller\Api;
use GatewayClient\Gateway;
use think\db\Query;
use think\Db;

/**
 *  Websocket接口
 */
class Lt extends Api
{
    protected $noNeedLogin = ['test'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        Gateway::$registerAddress = '127.0.0.1:1280';
    }


    /**
     * 先连接websocket  ws://60.205.8.40:7286
     * 绑定用户client_id （可以在登录成功的时候就执行最好）
     * @ApiMethod (POST)
     * @ApiParams (name="client_id",type="string",required=true,description="client_id")
     */
    public function bind()
    {
        if ($this->request->isPost()) {
            $uid = $this->auth->id;
            $uid = $uid ?  : 1;
            $client_id = $this->request->post('client_id');
            Gateway::bindUid($client_id, $uid);
            $this->success("绑定成功");
        }
    }

    /**
     * 发送消息
     * @ApiMethod (POST)
     * @ApiParams (name="to_user_id",type="string",required=true,description="接收者ID")
     * @ApiParams (name="content",type="string",required=true,description="消息内容")
     *
     */
    public function send(){
        if ($this->request->isPost()) {
            $to_user_id = $this->request->post('to_user_id');
            $content = $this->request->post('content');
            $friend = new Friend();
            $friend = $friend->where('user_id',$this->auth->id)
                ->where('friend_id',$to_user_id)->find();
            if (!$friend){
                Friend::create([
                    'user_id' => $this->auth->id,
                    'friend_id' => $to_user_id,
                ]);
                Friend::create([
                    'user_id' => $to_user_id,
                    'friend_id' => $this->auth->id
                ]);
            }
            $data = [
//                'type' => 'chatMessage', // 消息类型，chatMessage聊天消息，event事件消息
                'user_id' => $this->auth->id,
                'to_user_id' => $to_user_id,
                'content' => $content,
                'createtime' => time(),
            ];
            $model = new Msg();
            $model->save($data);
            $data['type'] = 'chatMessage';
            Gateway::sendToUid($to_user_id, json_encode($data));
            $this->success("发送成功");
        }
    }
    /**
     * 获取好友列表和最后一条消息
     * @ApiMethod (GET)
     */
    public function getFriend(){
        $list = Friend::alias('f')
            ->join('user u','u.id = f.friend_id')
            ->join('user_msg m','m.user_id = f.friend_id and m.to_user_id = f.user_id','left')
            ->where('f.user_id',$this->auth->id)
            ->group('f.friend_id')
            ->field('f.friend_id,u.nickname,u.avatar,m.content,m.createtime')
            ->select();
        foreach($list as $key => $val){
            $list[$key]['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
        }
        $this->success("获取成功",$list);
    }

    /**
     * 获取聊天记录
     * @ApiMethod (GET)
     * @ApiParams (name="to_user_id",type="string",required=true,description="接收者ID")
     * @ApiParams (name="page",type="string",required=true,description="页码")
     * @ApiParams (name="limit",type="string",required=true,description="每页条数")
     */
    public function getMsg()
    {
        $page = $this->request->get('page',1);
        $limit = $this->request->get('limit',10);

        $to_user_id = $this->request->get('to_user_id');
        $msg = new Msg();
        $list = $msg->where(function (Query $query) use ($to_user_id){
            $query->where('user_id',$this->auth->id)->where('to_user_id',$to_user_id);
        })->whereOr(function (Query $query) use ($to_user_id){
            $query->where('user_id',$to_user_id)->where('to_user_id',$this->auth->id);
        })->order('id desc')->page($page,$limit)->select();
        $list = array_reverse($list);
        foreach ($list as $key => $val){
            if($val['user_id'] == $this->auth->id){
                $select_user = DB::name("user")->where("id",$val['to_user_id'])->find();
            }else{
                $select_user = DB::name("user")->where("id",$val['user_id'])->find();
            }
            $list[$key]['avatar'] = $select_user['avatar'];
        }
        $this->success("获取成功", $list);
    }


    /**
     * 测试 给用户发送消息
     * @ApiParams (name="uid",type="string",required=true,description="用户ID")
     * @ApiParams (name="message",type="string",required=true,description="消息内容")
     * @ApiParams (name="type",type="string",required=true,description="消息类型")
     */
    public function test()
    {
        $uid = $this->request->get('uid');
        $message = $this->request->get('message');
        $type = $this->request->get('type');
        $uid = $uid ?: 1;
        $data = [
            'type' => $type,
            'message' => $message,
            'to_uid' => $uid,
            'to_client_id' => '',
            'to_type' => 'user',
        ];
        Gateway::sendToUid($uid, json_encode($data));
        $this->success("发送成功");
    }


}